﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace ConcordWinManager
{
    public class Rassrochka
    {
        public int MonthCount;

        public DateTime[] Months;
        public decimal[] PaymentAtMonth;

        /// <summary>
        /// Добаление в БД
        /// </summary>
        /// <param name="id_contract">ИД договора, к которому относится рассрочка</param>
        public void Insert(int id_contract)
        {
            StringBuilder query2 = new StringBuilder();

            for (int i = 0; i < Months.Length; i++)
            {
                query2.AppendLine(string.Format("INSERT INTO dbo.Oplata_plan (id_contract, Summ_plan, Date_plan) " +
                    " VALUES ('{0}','{1}','{2}')",
                    id_contract,
                    PaymentAtMonth[i].ToString().Replace(',', '.'),
                    string.Format("{0}-{1}-{2}", Months[i].Year, Months[i].Month, Months[i].Day)
                    ));
            }

            string s = query2.ToString();
            DB.execute_sql(query2.ToString());
        }

        /// <summary>
        /// Выборка рассрочки по ИД договора
        /// </summary>
        /// <param name="id_contract"></param>
        public void SelectByIdContract(int id_contract)
        {
            DataSet ds = new DataSet();
            string query = string.Format("SELECT * FROM dbo.Oplata_plan WHERE id_contract={0}", id_contract);

            DB.query_table(query, "dbo.Oplata_plan", ref ds);

            PaymentAtMonth = new decimal[24];
            Months = new DateTime[24];

            int k = 0;
            DateTime dt;
            if (ds.Tables.Count > 0)
            {
                foreach (DataTable dtable in ds.Tables)
                {
                    foreach (DataRow dr in dtable.Rows)
                    {
                        PaymentAtMonth[k] = decimal.Parse(dr["Summ_plan"].ToString());
                        if (DateTime.TryParse(dr["Date_plan"].ToString(), out dt))
                        {
                            Months[k] = dt;
                        }
                        k++;
                    }
                }
            }

            MonthCount = k;
        }
    }
}
